<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item label="会议室">
					<el-select 
                         v-model="selected" 
                         placeholder="请选择会议室" 
                    >
                        <div v-for="item in rooms" :key="item.id">
                            <el-option :label="item.roomName" :value="item.id">{{item.roomName}}</el-option>
                        </div>
					</el-select>
				</el-form-item>
                 <el-form-item prop="date">
                    <el-date-picker type="date" placeholder="选择日期" v-model="defaultDayDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getRoomDetails">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">申请预约</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="roomDetails" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column prop="roomName" label="会议室名称" min-width="120">
			</el-table-column>
			<el-table-column prop="theme" label="主题" min-width="180" sortable>
			</el-table-column>
            <el-table-column prop="startAt" label="开始时间" min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="endAt" label="结束时间" min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="applyUserName" label="申请人" min-width="120" sortable>
			</el-table-column>
		</el-table>

		<!--申请预约界面-->
		<el-dialog title="申请预约" v-model="addFormVisible" :close-on-click-modal="false" style="top: -5%;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="预约人" prop="name">
            <span>{{ ruleForm.applyUserName }}&nbsp;/&nbsp;{{ ruleForm.applyDeptName }}</span>
        </el-form-item>

        <el-form-item label="会议室">
			<el-select 
                v-model="ruleForm.selectedApply" 
                placeholder="请选择会议室" 
                @change="getApplyEquips"
            >
            <div v-for="item in ruleForm.applyRooms" :key="item.id">
                <el-option :label="item.roomName" :value="item.id">{{item.roomName}}</el-option>
            </div>
		    </el-select>
		</el-form-item>

        <el-form-item label="会议主题" prop="theme">
            <el-input v-model="ruleForm.theme" style="width:46%;"></el-input>
        </el-form-item>
        <el-form-item label="会议时间" required>
            <el-col :span="5">
                <el-form-item prop="date">
                    <el-date-picker
                        v-model="ruleForm.startAt"
                        type="datetime"
                        placeholder="开始时间"
                        default-time="">
                    </el-date-picker>
                </el-form-item>
            </el-col> 
            <el-col :span="5" style="margin-left: 100px;">
                <el-form-item prop="date">
                    <el-date-picker
                        v-model="ruleForm.endAt"
                        type="datetime"
                        placeholder="结束时间"
                        default-time="">
                    </el-date-picker>
                </el-form-item>
            </el-col> 
        </el-form-item>
        <el-form-item label="设备需求" prop="type">
            <ul style="list-style:none;padding-left:0px;margin-top:-10px;">
                <li v-for="item in ruleForm.equips" style="float: left;padding-left:10px;padding-right:10px;" :key="item">
                    {{ item }}
                </li>
            </ul>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="ruleForm.remark" style="width:46%;"></el-input>
        </el-form-item>
        <el-form-item>
            <!-- <router-link to="/user/My_appointment">

            <el-button type="primary" @click="submitForm()">立即创建</el-button>
            </router-link> -->
            <el-button type="primary" @click="submitForm()">立即创建</el-button>
            <el-button @click="resetForm">取消</el-button>
            <!-- <el-button @click.native="addFormVisible = false">取消</el-button> -->
        </el-form-item>
    </el-form>
        </el-dialog>
	</section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getRoomList, getRoomDetailsList, getApplyRoomList, getApplyEquipsList, getDepartmentList, submitFormList, addUser } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    name: ''
                },
                selected: '',
                
                rooms: [],
                defaultDayDate: new Date(),
                roomDetails:[],
                
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列
                ruleForm: {
                    name: '',
                    departmentName: '',
                    selectedApply: '',
                    applyRooms: [],
                    applyUserName: '',
                    applyUserId: '',
                    applyDeptName: '',
                    startAt: new Date(),
                    endAt: new Date(),
                    date: '',
                    time: '',
                    equips: [],
                    type: [],
                    remark: '',
                    roomName:'',
                    theme:''
                },
                rules: {
                    theme: [
                        { required: true, message: '请输入会议主题', trigger: 'change' }
                    ],

                },
                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
                //新增界面数据
                addForm: {
                    name: '',
                    sex: -1,
                    age: 0,
                    birth: '',
                    addr: ''
                },
            onClick(picker) {
              picker.$emit('pick', new Date());
            }

            }
        },
        methods: {
            //性别显示转换
            // formatSex: function (row, column) {
            //     return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            // },
            // handleCurrentChange(val) {
            //     this.page = val;
            //     this.getUsers();
            // },
            //获取会议室列表
            getRooms() {
                //NProgress.start();
                getRoomList().then((data) => {
                    var roomArr = eval(data);
                    
                    for(var i=0;i<roomArr.length;i++){

                        if( i == 0 ){
                            this.selected = roomArr[i].id;
                        }
                        if(roomArr[i].status == 0){
                            roomArr[i].status = '空闲';
                        }
                        
                        if(roomArr[i].status == 1){
                            roomArr[i].status = '被占用';
                        }
                        // alert(roomArr['i'].id);
                    }
                    this.rooms = roomArr;
                    this.listLoading = false;
                    this.getRoomDetails();
                });
            },
            //会议室详情界面
            getRoomDetails() {
        
                let roomId = this.selected;
                let date = dateFtt("yyyy-MM-dd",this.defaultDayDate);
                let para = { roomId, date };
             
                getRoomDetailsList(para).then((data) => {
                    var dataObj = eval(data);
                    if( dataObj.code == 200 ){
                        var arr = dataObj.bookDetailDTOList;
               
                        for(var i = 0;i < arr.length;i++){
                         
                            arr[i].startAt = format(parseInt(arr[i].startAt));
                            arr[i].endAt = format(parseInt(arr[i].endAt));                       
                        }
                        this.roomDetails = arr;
                        this.listLoading = false;
                    }
                    if( dataObj.code == 400 ){
                        // console.log(dataObj.msg);
                        this.roomDetails = '';
                    }
              
                    
                });
            },

            //获取当前登陆人员所在的部门
            getDepartment() {
                var user = sessionStorage.getItem('user');
                var userId = '';
                if (user) {
                     user = JSON.parse(user);
                     this.ruleForm.applyUserName = user.username || '';
                     this.ruleForm.applyUserId = user.id || '';
                     userId = user.id;
                }
                let para = { userId }
                // this.ruleForm.applyDeptName = 'a';
                getDepartmentList(userId).then((params) => {

                    this.ruleForm.applyDeptName = params.data.departmentName;
                });
            },
            //将会议室名称显示在“预约申请界面”
            getApplyRooms() {
                //NProgress.start();
                getApplyRoomList().then((data) => {
                    var roomArr = eval(data);
                    for(var i=0;i<roomArr.length;i++){
                        if( i == 0 ){
                            this.ruleForm.selectedApply = roomArr[i].id;
                        }   
                    }
                    this.ruleForm.applyRooms = roomArr;
                    this.listLoading = false;
                });
                this.getApplyEquips();
            },
            //将用户选择的会议室中的设备显示在“预约申请界面”
            getApplyEquips() {
                var roomId = this.ruleForm.selectedApply;
                // this.ruleForm.equips = ["八爪鱼",'投影仪'];
                getApplyEquipsList(roomId).then((params) => {
                    var equipsArr = [];
                    for(var i=0;i<params.length;i++){
                        equipsArr.push(params[i].name);
                    }
                    this.ruleForm.equips = equipsArr;
                    this.listLoading = false;
                });
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.ruleForm.theme = '';
                this.ruleForm.startAt = new Date();
                this.ruleForm.endAt = new Date();
                this.ruleForm.remark = '';
                this.getDepartment();
                this.getApplyRooms();
            },
            //新增
            addSubmit: function () {
                // this.$refs.addForm.validate((valid) => {
                //     if (valid) {
                //         this.$confirm('确认提交吗？', '提示', {}).then(() => {
                //             this.addLoading = true;
                //             //NProgress.start();
                //             let para = Object.assign({}, this.addForm);
                //             para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                //             // addUser(para).then((res) => {
                //             //     this.addLoading = false;
                //             //     //NProgress.done();
                //             //     this.$message({
                //             //         message: '提交成功',
                //             //         type: 'success'
                //             //     });
                //             //     this.$refs['addForm'].resetFields();
                //             //     this.addFormVisible = false;
                //             //     this.getUsers();
                //             // });
                //         });
                //     }
                // });
            },
            //重置
            resetForm() {
                this.addFormVisible = false;
                this.ruleForm.theme = '';
                this.ruleForm.startAt = new Date();
                this.ruleForm.endAt = new Date();
                this.ruleForm.remark = '';
                // this.ruleForm.theme.required = false;
                 this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            this.$refs['ruleForm'].resetFields();
                            this.ruleForm.theme.required = false;
                            // submitFormList(para).then((res) => {
                                // this.addLoading = false;
                                //NProgress.done();
                                // this.$message({
                                //     message: '提交成功',
                                //     type: 'success'
                                // });
                                // this.$refs['addForm'].resetFields();
                                // this.addFormVisible = false;
                                // this.getUsers();
                            // });
                        });
                    }
                });
            },
            //立即创建，申请预约
            submitForm() {

                //会议室id roomId
                var roomId = this.ruleForm.selectedApply;
                //申请人id applyUserId
                var applyUserId = this.ruleForm.applyUserId;
                //会议主题 theme
                var theme = this.ruleForm.theme;
                //开始时间 startAt
                var startAt = dateFtt("yyyy-MM-dd hh:mm:ss",this.ruleForm.startAt);
                //结束时间 endAt
                var endAt = dateFtt("yyyy-MM-dd hh:mm:ss",this.ruleForm.endAt);

                //备注
                var desc = this.ruleForm.remark;

                let para = { roomId, applyUserId, theme, startAt, endAt, desc };

                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            
                            this.addLoading = true;
                            //  this.$router.go('/user/My_appointment');
                          
                            submitFormList(para).then((data) => {
                            if(data.code == 200){
                                alert(data.msg);
                                this.$router.push({ path: '/user/My_appointment' });
                            }
                            if(data.code == 400){
                                alert(data.msg);
                            }
                            });
                            this.addFormVisible = false;
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
        },
        mounted() {
            this.getRooms();
            // this.getDepartment();
            // this.getApplyRooms();
            // this.getRoomDetails();
        }
    }

//将日期格式化为 2018-07-24
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 

//将时间戳转换成 2018-07-24 08:00:00 格式
function add0(m){return m<10?'0'+m:m }
function format(shijianchuo)
{
//shijianchuo是整数，否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}

</script>

<style scoped>

</style>